<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { rules } from './components/config'
import debounce from 'lodash.debounce'
import { getVerificationApi, getLoginApi, getInfoApi } from '@/services/login/login'

import { useMemberStore } from '@/stores'

const memberStore = useMemberStore()
const { ctx: that, proxy } = getCurrentInstance()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 表单数据
const loginForm = ref({
  captcha: '',
  password: '',
  phone: '',
  requestId: '',
  sysCode: 'PK_MEASURE',
  username: '',
  grant_type: 'password',
})
const loginCode = ref('')
const formRef = ref()
const agreement = ref(false)
const showPassword = ref(true)
const loading = ref(false)

// 查看密码
const changePassword = () => {
  showPassword.value = !showPassword.value
}

function generateRandomString(length) {
  let result = ''
  const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const charactersLength = characters.length

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }

  return result
}

// 获取图形验证码
const getVerification = async () => {
  // 获取图形验证码，需要重新生成一个id
  loginForm.value.requestId = generateRandomString(20)

  const res = await getVerificationApi({ requestId: loginForm.value.requestId })
  const arrBuf = new Uint8Array(res)
  loginCode.value = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrBuf)
}

// 切换图形验证码
const getDebounceCode = debounce(() => {
  // 需要防抖的函数逻辑
  getVerification()
}, 500)

// 获取用户信息
const getInfo = async () => {
  const res = await getInfoApi()
  memberStore.setUserInfo(res.data)
}
// 解决真机验证码不更新
const captchaInput = (e) => {
  loginForm.value.captcha = e.detail.value
}
const passwordInput = (e) => {
  loginForm.value.password = e.detail.value
}
const usernameInput = (e) => {
  loginForm.value.username = e.detail.value
}

// 提交
const onSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    agreement.value = true

    const res = await getLoginApi(loginForm.value)
    if (res.status == 200) {
      // 保存会员信息
      memberStore.setProfile(res.data)
      getInfo()
      // 成功提示
      uni.showToast({
        icon: 'success',
        title: '登录成功!',
      })
      setTimeout(() => {
        // 页面跳转
        uni.switchTab({ url: '/pages/index/index' })
      }, 500)
    } else {
      setTimeout(function () {
        loading.value = false
      }, 500)
      uni.showToast({
        icon: 'error',
        title: res.message,
      })
    }
  } catch (error) {
    setTimeout(function () {
      loading.value = false
    }, 500)
  }
}

onMounted(() => {
  getVerification()
})
</script>

<template>
  <view class="login" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <view class="title">
      <image src="../../static/login/logo.png" mode="scaleToFill" />
      <view class="name">
        <text class="color1">栖所</text>
        <text class="color2">养老</text>
      </view>
    </view>
    <uni-forms ref="formRef" :modelValue="loginForm" :rules="rules">
      <uni-forms-item name="username">
        <view class="phone">
          <image class="icon" src="../../static/login/shoujihao.png" mode="scaleToFill" />
          <input class="input" placeholder="请输入账号" @input="usernameInput" />
        </view>
      </uni-forms-item>
      <uni-forms-item name="password">
        <view class="phone">
          <image class="icon" src="../../static/login/mima.png" mode="scaleToFill" />
          <input
            class="input"
            :password="showPassword"
            :maxlength="16"
            placeholder="请输入密码"
            @input="passwordInput"
          />
          <image
            @tap="changePassword"
            class="showPassword"
            src="../../static/login/look.png"
            v-if="showPassword"
          />
          <image
            @tap="changePassword"
            class="showPassword"
            src="../../static/login/no.png"
            v-if="!showPassword"
          />
        </view>
      </uni-forms-item>
      <uni-forms-item name="captcha">
        <view class="phone">
          <image class="icon" src="../../static/login/yanzhengma.png" mode="scaleToFill" />
          <input
            class="input"
            :maxlength="4"
            placeholder="请输入图形验证码"
            @input="captchaInput"
          />
          <image @tap="getDebounceCode" class="code" :src="loginCode" />
        </view>
      </uni-forms-item>
      <uni-forms-item>
        <button class="button" :loading="loading" hover-class="button-hover" @click="onSubmit">
          登录
        </button>
      </uni-forms-item>
    </uni-forms>
    <view class="agreement" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <label class="radio"
        ><radio value="agreement" :checked="agreement" />我已阅读并同意<text>《用户协议》</text
        ><text>《隐私新政策》</text></label
      >
    </view>
  </view>
</template>

<style lang="scss">
.login {
  position: relative;
  height: 100vh;
  .title {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 200rpx;
    font-size: 42rpx;
    image {
      width: 207rpx;
      height: 128rpx;
    }
    .name {
      width: 207rpx;
      height: 138rpx;
      margin-top: 20rpx;
      text-align: center;
      .color1 {
        color: #3071ab;
      }
      .color2 {
        color: #7cb63b;
      }
    }
  }
  .uni-forms {
    width: 80%;
    margin: auto;
    .phone {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #eee;
      padding-bottom: 10rpx;
      position: relative;
      .icon {
        width: 34rpx;
        height: 34rpx;
        margin-right: 20rpx;
      }
      .showPassword {
        position: absolute;
        width: 34rpx;
        height: 34rpx;
        right: 0;
      }
      .code {
        position: absolute;
        right: 0;
        width: 180rpx;
        height: 60rpx;
      }
    }
    .button {
      color: #fff;
      border-radius: 50rpx;
      background-color: #108fe5;
    }
  }
  .agreement {
    position: absolute;
    left: 50rpx;
    bottom: 0rpx;
    .radio {
      color: #9a9a9a;
      text {
        color: #1a92e5;
      }
    }
  }
}
</style>
